package com.triones.ljr.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.triones.ljr.entity.bo.PolicyParams;
import com.triones.ljr.entity.dto.*;
import com.triones.ljr.entity.vo.*;
import com.triones.ljr.mapper.*;
import com.triones.ljr.service.PolicyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 我要获策
 */
@Service
@RequiredArgsConstructor
public class PolicyServiceImpl implements PolicyService {

    private final IndustryCodeMapper industryCodeMapper;

    private final PolicyMapper policyMapper;

    private final PolicyItemMapper policyItemMapper;

    private final CollectMapper collectMapper;

    private final DeclareAuditMapper declareAuditMapper;

    @Override
    public List<IndustryCodeDO> industryTreeList() {
        LambdaQueryWrapper<IndustryCodeDO> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(IndustryCodeDO::getParentId);
        List<IndustryCodeDO> dataList = industryCodeMapper.selectList(lqw);
        Map<Long, IndustryCodeDO> dataMap = dataList.stream()
            .collect(Collectors.toMap(IndustryCodeDO::getId, Function.identity()));
        List<IndustryCodeDO> treeList = new ArrayList<>();
        for (IndustryCodeDO node : dataList) {
            Long parentId = node.getParentId();
            if (parentId == null || parentId.equals(0L)) {
                treeList.add(node);
            } else {
                IndustryCodeDO parent = dataMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }
        return treeList;
    }

    @Override
    public TableDataInfo<CustomPolicyVO> pageList(PolicyParams params, PageQuery pageQuery) {
        Page<CustomPolicyVO> result = policyMapper.selectPageList(pageQuery.build(), params);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean add(PolicyDO dto) {
        return policyMapper.insert(dto) > 0;
    }

    @Override
    public PolicyVO getInfo(Long id) {
        return policyMapper.selectVoById(id);
    }

    @Override
    public boolean edit(PolicyDO dto) {
        return policyMapper.updateById(dto) > 0;
    }

    @Override
    public List<PolicyVO> list() {
        return policyMapper.selectVoList(new LambdaQueryWrapper<PolicyDO>()
            .eq(PolicyDO::getIsDel, "0")
            .eq(PolicyDO::getStatus,"0"));
    }

    @Override
    public boolean addItem(PolicyItemDO dto) {
        return policyItemMapper.insert(dto) > 0;
    }

    @Override
    public boolean checkItemNameUnique(PolicyItemDO dto) {
        boolean exist = policyItemMapper.exists(new LambdaQueryWrapper<PolicyItemDO>()
            .eq(PolicyItemDO::getItemName, dto.getItemName())
            .eq(PolicyItemDO::getPid, dto.getPid())
            .eq(PolicyItemDO::getIsDel, "0")
            .ne(ObjectUtil.isNotNull(dto.getId()), PolicyItemDO::getId, dto.getId()));
        return !exist;
    }

    @Override
    public TableDataInfo<CustomPolicyItemVO> itemPageList(PolicyItemDO dto, PageQuery pageQuery) {
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq(ObjectUtil.isNotNull(dto.getPid()),"tpi.pid", dto.getPid());
        wrapper.eq("tpi.is_del", "0");
        wrapper.like(ObjectUtil.isNotEmpty(dto.getItemName()),"tpi.item_name", dto.getItemName());
        wrapper.orderByAsc("tpi.pid").orderByAsc("tpi.create_time");
        Page<CustomPolicyItemVO> result = policyItemMapper.selectPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean editItem(PolicyItemDO dto) {
        return policyItemMapper.updateById(dto) > 0;
    }

    @Override
    public PolicyItemVO getItemInfo(Long id) {
        return policyItemMapper.selectVoById(id);
    }

    @Override
    public boolean removeItem(Long id) {
        PolicyItemDO policyItemDO = policyItemMapper.selectById(id);
        if (policyItemDO == null) {
            throw new ServiceException("数据不存在");
        }
        policyItemDO.setIsDel("1");
        return policyItemMapper.updateById(policyItemDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(Long id) {
        PolicyDO policyDO = policyMapper.selectById(id);
        if (policyDO == null) {
            throw new ServiceException("数据不存在");
        }
        List<PolicyItemDO> itemList = this.getItemList(id);
        if (itemList.size() > 0) {
            itemList.forEach(item -> {
                item.setIsDel("1");
            });
            policyItemMapper.updateBatchById(itemList);
        }
        policyDO.setIsDel("1");
        return policyMapper.updateById(policyDO) > 0;
    }

    @Override
    public List<PolicyItemDO> getItemList(Long pid) {
        return policyItemMapper.selectList(new LambdaQueryWrapper<PolicyItemDO>()
            .eq(PolicyItemDO::getPid, pid)
            .eq(PolicyItemDO::getIsDel, "0"));
    }

    @Override
    public TableDataInfo<CustomPolicyVO> apiPageList(PolicyParams params, PageQuery pageQuery) {
        Page<CustomPolicyVO> result = policyMapper.selectPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    public CustomPolicyVO getPolicyDetail(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        CustomPolicyVO vo = policyMapper.getPolicyDetail(id);
        if (vo != null) {
            vo.setPolicyItemList(policyItemMapper.selectList(new LambdaQueryWrapper<PolicyItemDO>()
                .eq(PolicyItemDO::getPid, id)
                .eq(PolicyItemDO::getIsDel, "0")));
        }
        CollectDO collectDO = collectMapper.selectOne(new LambdaQueryWrapper<CollectDO>()
            .eq(CollectDO::getPId, id).eq(CollectDO::getWxuId, loginUser.getUserId()).last("limit 1"));
        vo.setIsCollect(0);
        if (collectDO != null) {
            vo.setIsCollect(1);
        }
        return vo;
    }

    @Override
    public TableDataInfo<PolicyItemVO> apiItemPageList(String keyword, PageQuery pageQuery) {
        LambdaQueryWrapper<PolicyItemDO> lqw = Wrappers.lambdaQuery();
        lqw.isNotNull(PolicyItemDO::getDeclareTemplateId)
            .eq(PolicyItemDO::getIsDel, "0");
        lqw.like(StringUtils.isNotBlank(keyword), PolicyItemDO::getItemName, keyword);
        Page<PolicyItemVO> result = policyItemMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public CustomPolicyItemVO itemDetail(Long id) {
        return policyItemMapper.itemDetail(id);
    }

    @Override
    public List<CustomPolicyVO> policyListByIndustry(String industry) {
        return policyMapper.policyListByIndustry(industry);
    }

    @Override
    public List<CustomDeclareAuditVO> declareAuditList() {
        return declareAuditMapper.declareAuditList();
    }
}
